package net.gyapp.markim.module.contact;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.easyder.wrapper.base.view.WrapperSwipeActivity;
import com.easyder.wrapper.core.model.BaseVo;
import com.luck.picture.lib.permissions.RxPermissions;

import net.gyapp.markim.ApiConfig;
import net.gyapp.markim.R;
import net.gyapp.markim.core.ImHelper;
import net.gyapp.markim.module.basic.base.CommonPresenter;
import net.gyapp.markim.module.collect.UserIntroduceActivity;
import net.gyapp.markim.module.contact.vo.UserListVo;
import net.gyapp.markim.module.contact.vo.UserVo;
import net.gyapp.markim.module.mine.QrScanActivity;
import net.gyapp.markim.utils.RequestParams;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.winds.widget.usage.TitleView;

/**
 * Author:  winds
 * Data:    2018/7/31
 * Version: 1.0
 * Desc:
 */


public class ContactAddActivity extends WrapperSwipeActivity<CommonPresenter> implements TextView.OnEditorActionListener {

    @BindView(R.id.et_input)
    EditText etInput;
    @BindView(R.id.tv_user)
    TextView tvUser;

    public static Intent getIntent(Context context) {
        return new Intent(context, ContactAddActivity.class);
    }

    public static Intent getIntent(Context context, String userId) {
        return new Intent(context, ContactAddActivity.class).putExtra("userId", userId);
    }

    @Override
    protected int getViewLayout() {
        return R.layout.activity_contact_add;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        getContainerView().setBackgroundColor(ContextCompat.getColor(mActivity, R.color.colorFore));
        titleView.setCenterText("添加好友");
        etInput.setImeActionLabel("搜索", EditorInfo.IME_ACTION_SEARCH);
        etInput.setOnEditorActionListener(this);
        tvUser.setText(String.format("%1$s%2$s", "彩聊ID:", ImHelper.getSelf()));
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        String userId = intent.getStringExtra("userId");
        if (!TextUtils.isEmpty(userId)) {
            searchContact(userId);
        }
    }

    @Override
    public void showContentView(String url, BaseVo dataVo) {
        if (url.contains(ApiConfig.API_GET_USER_INFO)) {
            etInput.setText(null);
            processUserInfo((UserVo) dataVo);
        } else if (url.contains(ApiConfig.API_FIND_USER_FRIEND)) {
            etInput.setText(null);
            processList((UserListVo) dataVo);
        }
    }


    @OnClick({R.id.layout_scan, R.id.layout_mobile_contact})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_scan:
                startActivity(QrScanActivity.getIntent(mActivity));
                break;
            case R.id.layout_mobile_contact:
                checkPermission();
                break;
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH && v.getId() == R.id.et_input) {
            String s = etInput.getText().toString();
            if (!TextUtils.isEmpty(s)) {
                searchContactInfo(s);
            }
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10001 && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            if (uri != null) {
                Cursor cursor = getContentResolver()
                        .query(uri,
                                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
                                null, null, null);
                if (cursor.moveToNext()) {
                    String number = cursor.getString(0);
                    String name = cursor.getString(1);

                    showToast("name:" + name + "  mobile:" + number);
                }
            }
        }
    }

    private void searchContact(String s) {
        presenter.setNeedDialog(true);
        presenter.postData(ApiConfig.API_GET_USER_INFO, new RequestParams().put("userName", s).get(), UserVo.class);
    }

    private void searchContactInfo(String s) {
        presenter.setNeedDialog(true);
        presenter.postData(ApiConfig.API_FIND_USER_FRIEND, new RequestParams().put("searchInfo", s).get(), UserListVo.class);
    }


    private void processUserInfo(UserVo dataVo) {
        startActivity(UserIntroduceActivity.getIntent(mActivity, dataVo));
    }


    private void processList(UserListVo dataVo) {
        if (dataVo.findFriends != null && dataVo.findFriends.size() > 0) {
            startActivity(SearchResultActivity.getUserIntent(mActivity, dataVo.findFriends));
        }
    }


    private void checkPermission() {
        new RxPermissions(mActivity).request(Manifest.permission.READ_CONTACTS)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (!aBoolean) {
                            showToast("权限被拒绝");
                        }
                        onPermissionGain(aBoolean);
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast("权限被拒绝，请主动打开");
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void onPermissionGain(Boolean aBoolean) {
        if (aBoolean) {
            try {
                //跳转到系统联系人应用
                Intent intent = new Intent(Intent.ACTION_PICK,
                        ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, 10001);
            } catch (Exception e) {
            }
        }
    }
}
